package edu.gatech.cs2340.OregonTrail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ItemLoader extends DefaultHandler{
	
	private List<Item> items;
	private String tempNodeVal;
	private Item tempItem;
	
	public ItemLoader(){
		items = new ArrayList<Item>();
		tempNodeVal = new String();
	}
	
	public void loadItems(String fileName) throws SAXException, ParserConfigurationException, IOException{
		parseDocument(fileName);
	}
	
	//I throw my exceptions up in the air sometimes
	private void parseDocument(String fileName) throws SAXException, ParserConfigurationException, IOException{
		//I throw my exceptions up in the air sometimes
		SAXParserFactory saxParserFac = SAXParserFactory.newInstance();

		javax.xml.parsers.SAXParser parser = ((SAXParserFactory) saxParserFac).newSAXParser();
		parser.parse(fileName, this);
	}
	
	//Hi there, I'm your friendly neighbor event handlers.
	//SAX XML parser is the fast XML parser for java, running through the document on its own and being event driven
	//Downside? No modification. But, our XML is (should be) static, so it doesn't make sense to load it all into memory
	//for the unused benefit of making changes
	
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		tempNodeVal = "";
		
		if(qName.equalsIgnoreCase("Item")){
			tempItem = new Item();
		}
	}
	
	public void characters(char[] ch, int start, int length) throws SAXException{
		//Ha! Look at that string. It thinks it's similar to a C string. Silly string, you're in Java
		//Do we actually need to use this constructor? Nah, just the ch will work but event call is perfectly designed
		//to work with it, so why not
		tempNodeVal = new String(ch, start, length);
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {

		if(qName.equalsIgnoreCase("Item")){
			items.add(tempItem);
		}
		else if(qName.equalsIgnoreCase("Name")){
			tempItem.setItemName(tempNodeVal);
		}
		else if(qName.equalsIgnoreCase("Cost")){
			tempItem.setBaseCost(Integer.parseInt(tempNodeVal));
		}
		else if(qName.equalsIgnoreCase("Weight")){
			tempItem.setWeight(Integer.parseInt(tempNodeVal));
		}
	}
	
	public List<Item> getItems(){
		return items;
	}
}
	
	